/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AspectDefDlg.java
 *
 * Created on 3 Jan, 2010, 12:23:55 PM
 */
package jaspect;

import jaspect.control.ConfigurationBuilder;
import jaspect.model.AspectConfiguration;
import jaspect.model.AspectMethod;
import java.awt.Frame;
import java.awt.event.MouseEvent;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

/**
 *
 * @author Arjun
 */
public class AspectDefDlg extends javax.swing.JDialog {

    Frame jf;
    private Main parentF;
    DefaultListModel modMethodsList = new DefaultListModel();
    private AspectConfiguration config = new AspectConfiguration();

    /** Creates new form AspectDefDlg
     * @param parent
     * @param modal
     */
    public AspectDefDlg(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        jf = parent;
        initComponents();
         for(int i=0; i<aspectParams.getRowCount(); i++)
        {
            aspectParams.setValueAt("", i, 0);
            aspectParams.setValueAt("", i, 1);
        }
        listMethods.setModel(modMethodsList);
        modMethodsList.clear();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.JLabel interceptModeL = new javax.swing.JLabel();
        aspectName = new javax.swing.JTextField();
        aspectNameL = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        aspectParams = new javax.swing.JTable();
        serviceClass = new javax.swing.JTextField();
        serviceClassL = new javax.swing.JLabel();
        javax.swing.JButton createAspect = new javax.swing.JButton();
        buttonDefineMethod = new javax.swing.JButton();
        cbInterceptMode = new javax.swing.JComboBox();
        lMethods = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        listMethods = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Define aspect configuration");

        interceptModeL.setText("Intercept Mode");

        aspectNameL.setText("AspectName");

        aspectParams.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Param name", "Param value"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(aspectParams);

        serviceClassL.setText("Service Class");

        createAspect.setText("Save");
        createAspect.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                createAspectMouseClicked(evt);
            }
        });
        createAspect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createAspectActionPerformed(evt);
            }
        });

        buttonDefineMethod.setText("Define Method");
        buttonDefineMethod.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDefineMethodActionPerformed(evt);
            }
        });

        cbInterceptMode.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Method", "Member", " " }));

        lMethods.setText("Method List");

        listMethods.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listMethods.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listMethodsMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(listMethods);

        jScrollPane3.setViewportView(jScrollPane2);

        jLabel1.setText("Aspect Parameters");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(buttonDefineMethod)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 234, Short.MAX_VALUE)
                                .addComponent(createAspect)
                                .addGap(33, 33, 33))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(13, 13, 13)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(serviceClassL, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(interceptModeL, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                                    .addComponent(aspectNameL, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(serviceClass, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                                    .addComponent(aspectName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                                    .addComponent(cbInterceptMode, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(59, 59, 59)))
                        .addGap(57, 57, 57))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(13, 13, 13)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lMethods))
                        .addGap(59, 59, 59)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(aspectName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(aspectNameL))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(serviceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(serviceClassL))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(interceptModeL)
                    .addComponent(cbInterceptMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lMethods)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(createAspect)
                    .addComponent(buttonDefineMethod, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-491)/2, (screenSize.height-386)/2, 491, 386);
    }// </editor-fold>//GEN-END:initComponents

    private void createAspectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createAspectMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_createAspectMouseClicked

    private void createAspectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createAspectActionPerformed
        // TODO add your handling code here
this.getParentF().setAjxmlFile("out.ajxml");
        Properties ps = new Properties();

        config.setName(aspectName.getText());
        config.setServiceClassName(serviceClass.getText());
        config.setMode(AspectConfiguration.InterceptMode.valueOf(cbInterceptMode.getSelectedItem().toString().toLowerCase()));

        try {
            for (int ri = 0; ri < aspectParams.getRowCount(); ri++) {
                if (aspectParams.getValueAt(ri, 0) == "" || aspectParams.getValueAt(ri, 1) == "") {
                    break;
                }
                String nam, val;
                nam = aspectParams.getValueAt(ri, 0).toString();
                val = aspectParams.getValueAt(ri, 1).toString();
                ps.setProperty(nam, val);
              

            }

            config.setParams(ps);
            save();
            parentF.addToAspectList(config);
            this.setVisible(false);
        } catch (Exception ie) {
             System.out.println("AspectDefDlg " +ie);
        }
    }//GEN-LAST:event_createAspectActionPerformed

    private void buttonDefineMethodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDefineMethodActionPerformed
        // TODO add your handling code here:
        AspectMethodGUI d = new AspectMethodGUI(jf, this, true);
        d.setVisible(true);
    }//GEN-LAST:event_buttonDefineMethodActionPerformed

    @SuppressWarnings("static-access")
    private void listMethodsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listMethodsMouseClicked
        // TODO add your handling code here:
        if ((MouseEvent.BUTTON3 == evt.getButton()) && (listMethods.getSelectedIndex() >= 0)) {
            AspectMethodGUI d = new AspectMethodGUI(jf, this, true);
            d.setMethod((AspectMethod) listMethods.getSelectedValue());
           // modMethodsList.removeElement((AspectMethod) listMethods.getSelectedValue());
            d.setVisible(true);
        }

    }//GEN-LAST:event_listMethodsMouseClicked
    /**
     *
     * @param a
     */
    public void setMethod(AspectMethod a) {
       
          for(int i = 0; i < modMethodsList.getSize(); i++)
          {
              if(a.getMethodName().equals(((AspectMethod)modMethodsList.elementAt(i)).getMethodName()))
              {
                  config.getMethods().remove(((AspectMethod)modMethodsList.getElementAt(i)).getMethodName());
                 modMethodsList.removeElement(modMethodsList.elementAt(i));
                  break;
              }

          }
        

        config.getMethods().put(a.getMethodName(), a);
        modMethodsList.addElement(a);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                AspectDefDlg dialog = new AspectDefDlg(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    /**
     * @return the config
     */
    public AspectConfiguration getConfig() {
        return config;
    }

    /**
     * @param config the config to set
     */
    public void setConfig(AspectConfiguration config) {
        this.config = config;
        aspectName.setText(config.getName());
        serviceClass.setText(config.getServiceClassName());
        if (config.getMode().toString().equals("method")) {
            cbInterceptMode.setSelectedItem("Method");
        } else if (config.getMode().toString().equals("member")) {
            cbInterceptMode.setSelectedItem("Member");
        }
        Properties ps = config.getParams();
        Enumeration en = ps.propertyNames();
        for (int i = 0; i < ps.size(); i++) {
            String se = en.nextElement().toString();
            aspectParams.setValueAt(se, i, 0);
            aspectParams.setValueAt(ps.getProperty(se), i, 1);
        }
        for (AspectMethod am : config.getMethods().values()) {
            modMethodsList.addElement(am);
        }


    }

    /**
     *
     * @param method
     */
    public void addMethod(AspectMethod method) {
        modMethodsList.addElement(method);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField aspectName;
    private javax.swing.JLabel aspectNameL;
    private javax.swing.JTable aspectParams;
    private javax.swing.JButton buttonDefineMethod;
    private javax.swing.JComboBox cbInterceptMode;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lMethods;
    private javax.swing.JList listMethods;
    private javax.swing.JTextField serviceClass;
    private javax.swing.JLabel serviceClassL;
    // End of variables declaration//GEN-END:variables

    private void save() {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setProjectDir(Main.projectFolder);
         Map<String, AspectConfiguration> mp = new HashMap<String, AspectConfiguration>();
        mp.put(config.getName(), config);
        cb.setAspects(mp);
        try {
            cb.writeToFile();
        } catch (Exception ex) {
            System.out.println(ex);
            Logger.getLogger(AspectDefDlg.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @return the parentF
     */
    public Main getParentF() {
        return parentF;
    }

    /**
     * @param parentF the parentF to set
     */
    public void setParentF(Main parentF) {
        this.parentF = parentF;
    }
}
